<template>
  <div class="app-container">

    <!-- <div class="flex">
      <div class="label">内容：</div>
      <div class="custom-tag ">
        <el-radio-group v-model="radioCarCon" size="large">
          <el-radio-button :label="item.label" :value="item.label" v-for="(item,index) in carTypeList" :key="index"
            @click="bindCarRadio(item.label,item.value,index)" />
        </el-radio-group>
      </div>
    </div> -->
    <div class="header-cus">{{radioCarCon}}</div>
    <!-- <el-divider /> -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <div class="flex input-height align-center">
        <div class="label" v-if="deptId==101">收费站：</div>
        <div class="align-center" v-if="deptId==101">
          <el-tree-select v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
            class="margin-right" placeholder="请选择部门" check-strictly clearable @change="bindChangeTree($event,'deptId')" />
        </div>
        <div class="label">时间：</div>
        <div class="align-center">
          <el-radio-group v-model="cycleRadio" @change="bindchangeDate" class="margin-right">
            <el-radio-button label="day" v-if="route.query.type==1">本日</el-radio-button>
            <el-radio-button label="week" >本周</el-radio-button>
            <!-- <el-radio-button label="weekUp" v-if="radioIndex==1">上周</el-radio-button>
            <el-radio-button label="monthUp" v-if="radioIndex==2">上月</el-radio-button> -->
            <el-radio-button label="month" >本月</el-radio-button>
            <el-radio-button label="season">本季</el-radio-button>
            <el-radio-button label="year">本年</el-radio-button>
          </el-radio-group>
          <el-date-picker style="margin-right:8px" v-model="dateSection" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
            @change="bindChangeAllDate" />
        </div>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="[radioIndex==0?'excess:abnormal:add':radioIndex==2?'excess:illegal:add':'excess:handover:add']">上报</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="[radioIndex==0?'excess:abnormal:export':radioIndex==2?'excess:illegal:export':'excess:handover:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <Custable :loading="loading" :content="goOutContent" :list="tableData" :queryParams="queryParams" :total="total" @getList="getList">
      <template #operation="scope">
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
          v-hasPermi="[ radioIndex==0?'excess:abnormal:edit':radioIndex==2?'excess:illegal:edit':'excess:handover:edit']">修改</el-button>
        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
          v-hasPermi="[ radioIndex==0?'excess:abnormal:remove':radioIndex==2?'excess:illegal:remove':'excess:handover:remove']">删除</el-button>
      </template>
    </Custable>

    <Mask v-if="dialogVisible" :dialogVisible="dialogVisible" @handleClose="handleClose" :queryParams="queryParams" :rowDetails="rowDetails" :rules="rules"
      :interface="carTypeList[radioIndex].interface" :formItemConfig="formItemConfig" />

  </div>
</template>


<script setup>
import moment from 'moment'
import { listAbnormal, delAbnormal, listIllegal, delIllegal, listHandover, delHandover } from "@/api/government/seeping";
import { deptTreeSelect } from "@/api/system/user";
import useUserStore from '@/store/modules/user'
import Custable from "@/components/Custom/Custable";
import Mask from "./components/Mask";
import config from "./config"
import { ref } from 'vue';

const route = useRoute();
const { proxy } = getCurrentInstance()
const { sys_yes_no } = proxy.useDict("sys_yes_no");
const userStore = useUserStore()
const queryParams = ref({ "startDate": '', "endDate": '', pageNum: 1, pageSize: 10 })
const radioCarCon = ref('入口治超轴重异常数据日报表(日）')
const carTypeList = ref([
  { label: '入口治超轴重异常数据日报表(日）', value: "0", interface: 'Abnormal' },
  { label: '岀口疑似违法超限运输车辆移交信息汇总（周）', value: "1", interface: 'Handover' },
  { label: '出口疑似违法超限运输信息汇总（月）', value: "2", interface: 'Illegal' }
])

const cycleRadio = ref('day')
const dialogVisible = ref(false)
const goOutContent = ref(config.goOutContent1)
const formItemConfig = ref(config.formItemConfig1)
const loading = ref(false)
const deptOptions = ref([])
const tableData = ref([])
const total = ref(0)
const rowDetails = ref({})
const dateSection = ref([])
const radioIndex = ref(0)
const methods = ref({ listAbnormal, delAbnormal, listIllegal, delIllegal, listHandover, delHandover })
const rules = ref(config.rules)
const deptId = ref()

// 分类



const bindCarRadio = (name, val, index) => {
  queryParams.value.enStation = null;
  queryParams.value.deptId = null;
  queryParams.value.exStation = null;
  goOutContent.value = config[`goOutContent${(Number(index) + 1)}`];
  formItemConfig.value = config[`formItemConfig${(Number(index) + 1)}`];
  rules.value = val == 1 ? {} : config.rules;
  radioIndex.value = val;
  tableData.value = [];

  cycleRadio.value = "day"
    bindchangeDate("day")

}


/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
    config.formItemConfig1[1].options = deptOptions.value;
    config.formItemConfig2[2].options = deptOptions.value;
    config.formItemConfig2[1].onChange = (val) => {
      rowDetails.value.statisticalTime = val[0]
      rowDetails.value.statisticalEndTime = val[1]
    }
    config.formItemConfig3[1].onChange = (val) => {
      rowDetails.value.statisticalTime = val[0]
      rowDetails.value.statisticalEndTime = val[1]
    }
    config.formItemConfig3[2].options = deptOptions.value;
    config.formItemConfig3[config.formItemConfig3.length - 2].options = sys_yes_no.value;
    config.formItemConfig1.forEach(item => {
      if (item.label && item.label.indexOf('是否') != -1) {
        item.options = sys_yes_no.value
      }
    });
  });
};
/** 查询异常标签稽核台账列表 */
function getList(abutment) {
  loading.value = true;
  if(!abutment||methods.value[abutment]){
    abutment=radioIndex.value==0?'listAbnormal':radioIndex.value==1?'listHandover':'listIllegal';    
  }
  methods.value[abutment](queryParams.value).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除异常标签稽核台账编号为"' + _ids + '"的数据项？').then(function () {
    return methods.value['del' + carTypeList.value[radioIndex.value].interface](_ids);
  }).then(() => {
    getList('list' + carTypeList.value[radioIndex.value].interface);
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}



const bindChangeAllDate = (val) => {

  dateSection.value = [moment(val[0]).format("YYYY-MM-DD"), moment(val[1]).format("YYYY-MM-DD")]
  queryParams.value.startDate = dateSection.value[0];
  queryParams.value.endDate = dateSection.value[1];
}

/** 搜索按钮操作 */
function handleQuery() {
  getList('list' + carTypeList.value[radioIndex.value].interface)
};
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = { pageNum: 1, pageSize: 10 };
  cycleRadio.value = "day";
  proxy.resetForm("queryRef");
  init()
  handleQuery();
};
const handleAdd = () => {
  let startDate = moment().format("YYYY-MM-DD");
  if (radioIndex.value == 0) {
    rowDetails.value = { enStation: deptId.value, reportDate: startDate };
  } else if (radioIndex.value == 1) {
    const currentDate = moment();
    // 获取上周的开始日期（周一）
    const lastWeekStartDate = moment(currentDate).clone().subtract(1, 'weeks').startOf('isoWeek').format("YYYY-MM-DD");
    // 获取上周的结束日期（周天）
    const lastWeekEndDate = moment(currentDate).clone().subtract(1, 'weeks').endOf('isoWeek').format("YYYY-MM-DD");
    rowDetails.value = { reportDate: startDate, exStation: deptId.value, statistical: [lastWeekStartDate, lastWeekEndDate], statisticalTime: lastWeekStartDate, statisticalEndTime: lastWeekEndDate };
  } else {
    let startDate2 = moment().subtract(1, 'months').format("YYYY-MM") + '-01';
    let endDate = moment().subtract(1, 'months').endOf('month').format('YYYY-MM-DD')
    rowDetails.value = { reportDate: startDate, exStation: deptId.value, statistical: [startDate2, endDate], statisticalTime: startDate2, statisticalEndTime: endDate };
  }
  dialogVisible.value = true;
}
const handleUpdate = (data) => {
  dialogVisible.value = true;
 
  rowDetails.value = data;
  rowDetails.value.statistical=[data.statisticalTime,data.statisticalEndTime]
}

const handleClose = () => {
  dialogVisible.value = false;
  getList('list' + carTypeList.value[radioIndex.value].interface)
}


/** 导出按钮操作 */
function handleExport() {
  let url = radioIndex.value == 0 ? 'abnormal/export' : radioIndex.value == 1 ? 'handover/export' : 'illegal/export'
  proxy.download(url, {
    ...queryParams.value
  }, `${radioIndex.value == 0 ? '入口治超轴重异常数据日报表' : radioIndex.value == 1 ? '岀口疑似违法超限运输车辆移交信息汇总' : '出口疑似违法超限运输信息汇总'}_${new Date().getTime()}.xlsx`)
}
const bindchangeDate = (val) => {
  let date = new Date();
  let year = date.getFullYear();
  let params = {}
  if (val == 'day') {
    params.startDate = moment().format("YYYY-MM-DD")
    params.endDate = moment().format("YYYY-MM-DD");
  } else if (val == 'week') {
    params.startDate = moment().startOf('week').format('YYYY-MM-DD');
    params.endDate = moment().endOf('week').format('YYYY-MM-DD')
  } else if (val == 'month') {

    params.startDate = moment().startOf('month').format('YYYY-MM-DD');
    params.endDate = moment().endOf('month').format('YYYY-MM-DD')
  } else if (val == 'monthUp') {
    params.startDate = moment().subtract(1, 'months').format("YYYY-MM") + '-01';
    params.endDate = moment().subtract(1, 'months').endOf('month').format('YYYY-MM-DD')
  } else if (val == 'season') {
    let startQuarter = moment(moment().quarter(moment().quarter()).startOf('quarter').valueOf()).format('YYYY-MM-DD');
    let endQuarter = moment(moment().quarter(moment().quarter()).endOf('quarter').valueOf()).format('YYYY-MM-DD');
    params.startDate = startQuarter
    params.endDate = endQuarter
  } else if (val == 'weekUp') {
    const currentDate = moment();
    // 获取上周的开始日期（周一）
    const lastWeekStartDate = moment(currentDate).clone().subtract(1, 'weeks').startOf('isoWeek').format("YYYY-MM-DD");
    // 获取上周的结束日期（周天）
    const lastWeekEndDate = moment(currentDate).clone().subtract(1, 'weeks').endOf('isoWeek').format("YYYY-MM-DD");
    params.startDate = lastWeekStartDate;
    params.endDate = lastWeekEndDate
  } else {
    params.startDate = year + '-01-01'
    params.endDate = year + '-12-31'
  }
  dateSection.value = [moment(params.startDate).format("YYYY-MM-DD"), moment(params.endDate).format("YYYY-MM-DD")]
  queryParams.value = { ...queryParams.value, ...params }; getList('list' + carTypeList.value[radioIndex.value].interface)


}



const bindChangeTree = (val, name) => {
  queryParams.value[name] = val;
  if (radioIndex.value == 0) {
    queryParams.value.enStation = val;
    queryParams.value.exStation = null;
  } else {
    queryParams.value.enStation = null;
    queryParams.value.exStation = val;
  }
}
const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptId.value = res.user.dept.deptId;
      rowDetails.value.enStation = deptId.value;
      queryParams.value.deptId= res.user.dept.deptId;
    }

  })
}

const init = () => {
  let startDate = moment().format("YYYY-MM-DD");
  dateSection.value = [startDate, startDate]
  queryParams.value.startDate = startDate;
  queryParams.value.endDate = startDate;
  rowDetails.value.reportDate = startDate;
}



if (route&&route.query&&route.query) {
  let indexType=Number(route.query.type)-1
  radioCarCon.value=carTypeList.value[indexType].label
  bindCarRadio('',indexType,indexType)
}

getDeptTree()
getDeptId()
init()
getList('listAbnormal')
</script>

<style scoped>
.flex {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.flex .label {
  color: #333;
  font-size: 14px;
}

/deep/.padding .el-radio-button--large .el-radio-button__inner {
  padding: 8px 19px;
}
/deep/ .custom-tag .el-radio-button--large .el-radio-button__inner {
  min-width: 60px;
  height: 32px;
  line-height: 32px;
  margin: 0 4px 0;
  padding: 0 10px;
  border: 1px solid #e4e4e4;
  font-size: 14px;
}
/deep/ .custom-tag .el-radio-button--large.is-active .el-radio-button__inner {
  background: #fff;
  border: 1px solid #246bcc;
  color: #246bcc;
  position: relative;
}

/deep/
  .custom-tag
  .el-radio-button--large.is-active
  .el-radio-button__inner:after {
  content: "";
  position: absolute;
  top: 0px;
  right: 0px;
  border-top: 20px solid #246bcc;
  border-left: 20px solid transparent;
}
/deep/
  .custom-tag
  .el-radio-button--large.is-active
  .el-radio-button__inner:before {
  content: "";
  position: absolute;
  width: 5px;
  height: 6px;
  background: transparent;
  top: 2px;
  right: 4px;
  border: 1px solid white;
  border-top: none;
  border-right: none;
  transform: rotate(-55deg);
  z-index: 9;
}

.margin-right {
  margin-right: 8px;
}
/deep/ .input-height .el-input__wrapper {
  height: 32px;
}
/deep/ .input-height .el-date-editor.el-input {
  height: 32px;
}
.margin-right-lg {
  margin-right: 32px;
}
.cursor {
  cursor: pointer;
}
.flex-end {
  margin-left: auto;
}
.active {
  position: relative;
}
.active::before {
  content: "";
  display: block;
  width: 50px;
  height: 2px;
  border-radius: 2px;
  background: var(--el-color-primary);
  position: absolute;
  bottom: 3px;
  left: 50%;
  transform: translateX(-50%);
}
.align-center {
  display: flex;
  align-items: center;
}
.header-cus{
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
}
</style>